﻿/*******************************************************************
 *     JameE
 *******************************************************************
  Copyright 2010 Clifford Champion and JameE contributors.
  
  This file is part of JameE.
  
  JameE is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  JameE is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with JameE.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************/


$class_static(
"JameE.Utils.PerformanceTimer",
{
	/////////////////////
	// FIELDS
	/////////////
	_hash_oTimersByName: null,
	_hash_oDurationsByName: null,


	/////////////////////
	// CONSTRUCTORS
	/////////////
	_ctor: function () {
		this._hash_oTimersByName = {};
		this._hash_oDurationsByName = {};
	},


	/////////////////////
	// METHODS
	/////////////
	beginTimer: function (strTimerName) {
		var arr_oStartTimesStack;
		arr_oStartTimesStack = this._hash_oTimersByName[strTimerName] || null;
		if (arr_oStartTimesStack === null) {
			this._hash_oTimersByName[strTimerName] = arr_oStartTimesStack = [];
		}
		arr_oStartTimesStack.push(new Date());
	},

	endTimer: function (strTimerName) {
		var oDateTimeNow = new Date();

		var arr_oStartTimesStack;
		arr_oStartTimesStack = this._hash_oTimersByName[strTimerName] || null;
		if (arr_oStartTimesStack === null) {
			throw new Error("Timer not found.");
		}

		if (arr_oStartTimesStack.length === 0) {
			throw new Error("Timer already ended.");
		}

		var oDateTimeStarted = arr_oStartTimesStack.pop();

		// save the duration
		var arr_oDurations;
		arr_oDurations = this._hash_oDurationsByName[strTimerName] || null;
		if (arr_oDurations === null) {
			this._hash_oDurationsByName[strTimerName] = arr_oDurations = [];
		}
		arr_oDurations.push(oDateTimeNow.getTime() - oDateTimeStarted.getTime());
	},

	getAverageDuration: function (strTimerName) {
		$require_type(strTimerName, "string");

		var arr_oDurations = this._hash_oDurationsByName[strTimerName] || null;
		if (arr_oDurations === null || arr_oDurations.length === 0) {
			return Number.NaN;
		}

		var fTotal = 0.0;
		var iDurations = arr_oDurations.length;
		for (var i = 0; i < iDurations; ++i) {
			fTotal = fTotal + arr_oDurations[i];
		}
		fTotal = fTotal / iDurations;
		return fTotal;
	}
});

$timer_begin = function (strTimerName) { };
$timer_end = function (strTimerName) { };


$include_notify("Utils/PerformanceTimer.js");

